package com.yl.chainStore.control.customer

import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.yl.chainStore.common.Constants
import com.yl.chainStore.common.Constants.StrShow.Companion.CUSTOMER_MOBILE_SELF
import com.yl.chainStore.common.Constants.StrShow.Companion.CUSTOMER_MOBILE_TO_CUSTOMER_TYPE_SELF_ID
import com.yl.chainStore.common.Constants.StrShow.Companion.CUSTOMER_TO_CUSTOMER_SOURCE_ASSOCIATED
import com.yl.chainStore.common.enums.TypeEnum
import com.yl.chainStore.control.BaseCtrl
import com.yl.chainStore.entity.customer.*
import com.yl.chainStore.entity.user.CompanyUserCustomerSelectLog
import com.yl.chainStore.pojo.vo.customer.*
import com.yl.chainStore.pojo.vo.user.CompanyUserCustomerSelectLogSelectVo
import com.yl.chainStore.services.*
import com.yl.chainStore.services.sick.ICustomerSubscribeLogService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import com.yl.common.getContext
import com.yl.users.common.annotations.PermsCode
import com.yl.users.services.ICompanyDeptService
import com.yl.users.services.ICompanyUserService
import org.springframework.transaction.annotation.Transactional
import org.springframework.transaction.interceptor.TransactionAspectSupport
import org.springframework.web.bind.annotation.*


/**
 * 客户信息管理视图
 */
@RestController
@RequestMapping("customer/info")
open class CustomerInfoController(
	private val iWebCompanyService: IWebCompanyService,
	private val iWebCompanyDeptService: IWebCompanyDeptService,
	private val iCompanyUserService: ICompanyUserService,
	private val iWebCompanyUserService: IWebCompanyUserService,
	private val iCustomerInfoService: ICustomerInfoService,
	private val iCompanyDictionaryService: ICompanyDictionaryService,
	private val iCustomerSubscribeLogService: ICustomerSubscribeLogService,
	private val iSysNumGeneratorService: ISysNumGeneratorService,
	private val iCompanyDeptService: ICompanyDeptService,
) : BaseCtrl() {

	/**
	 * 创建一个患者
	 */
	@PostMapping("createCustomer")
	@Transactional(rollbackFor = [Exception::class])
	@PermsCode("customer:info:add")
	open fun createCustomer(@RequestBody vo: CustomerInfoSaveVo): ResponseBody {
		//三级来源处理
		val customerSource = vo.customerInfo.sourceInsert
		vo.customerInfo.historySickNum = vo.customerInfo.historySickNum.replace(" ","")
		if (customerSource != null && customerSource.isNotEmpty()) {
			val sourceValues = customerSource.split("|")
			vo.customerInfo.firstSource = sourceValues[0]
			if (sourceValues.size > 1) {
				vo.customerInfo.secondSourceId = sourceValues[1].toLong()
			}
			if (sourceValues.size > 2) {
				val secondSource = iCustomerInfoService.getCustomerSecondSourceById(vo.customerInfo.secondSourceId!!)
				if (secondSource != null) {
					when (secondSource.subType) {
						TypeEnum.CUSTOMER_INFO_SOURCE_COMPANY_USER -> {
							vo.customerInfo.sourceCompanyUserId = sourceValues[2].toLong()
						}
						TypeEnum.CUSTOMER_INFO_SOURCE_CUSTOMER_INFO -> {
							vo.customerInfo.sourceCustomerId = sourceValues[2].toLong()
						}
						else -> {
							vo.customerInfo.sourceDistId = sourceValues[2].toLong()
						}
					}
				}
			}
		}
		//添加基本信息
		val addRes = iWebCompanyService.addCustomer(vo.customerInfo)
		if (addRes.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return addRes
		}
		if (vo.customerInfo.sourceCustomerId != null) {
			iCustomerInfoService.addAssociatedCustomer(
				CustomerInfoAssociated(
					id = 0,
					customerId = vo.customerInfo.id,
					associatedCustomerId = vo.customerInfo.id,
					associatedName = CUSTOMER_TO_CUSTOMER_SOURCE_ASSOCIATED
				)
			)
		}
		//设置手机和电话
		if (vo.customerInfo.mobileNum != null) {
			val setMobile = iCustomerInfoService.setMobile(vo.customerInfo.id, vo.customerInfo.mobileNum!!)
			if (setMobile.bodyIsError()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return setMobile
			}
		}
		if (vo.customerInfo.phone != null) {
			val setPhone = iCustomerInfoService.setPhone(vo.customerInfo.id, vo.customerInfo.phone!!)
			if (setPhone.bodyIsError()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return setPhone
			}
		}


		vo.deptConfig.customerId = vo.customerInfo.id
		val bindCustomer = iWebCompanyDeptService.setDeptConfig(vo.deptConfig)
		if (bindCustomer.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return bindCustomer
		}
		vo.records.customerId = vo.customerInfo.id
		val createMedicalRecords = iCustomerInfoService.createMedicalRecords(vo.records)
		if (createMedicalRecords.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return createMedicalRecords
		}

		val mutableMapOf = mutableMapOf<String, Any>()
		mutableMapOf["id"] = vo.customerInfo.id
		mutableMapOf["name"] = vo.customerInfo.name
		return returnSuccess(mutableMapOf)
	}

	/**
	 * 获取患者明细
	 */
	@GetMapping("getCustomerInfoDetail/{id}")
	@Transactional
	open fun getCustomerInfoDetail(@PathVariable id: Long): ResponseBody {
		val info = iCustomerInfoService.getById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND, "未找到患者信息")
		val config = iWebCompanyDeptService.getCustomerDeptConfig(id, getContext().subCompanyId)
		iCustomerInfoService.getMobileStr(info)
		iCustomerInfoService.getPhoneStr(info)
		info.recommendedCustomerCount = iCustomerInfoService.getRecommendedCustomerCount(id)
		return returnSuccess(
			CustomerInfoResultVo(
				customerInfo = info,
				deptConfig = config
			)
		)
	}

	/**
	 * 获取被推荐列表
	 */
	@GetMapping("getRecommendedCustomerList/{id}")
	@Transactional
	open fun getRecommendedCustomerList(@PathVariable id: Long): ResponseBody {
		val recommendedCustomerList = iCustomerInfoService.getRecommendedCustomerList(id)
		for (info in recommendedCustomerList) {
			iCustomerInfoService.getMobileFirstStr(info)
		}
		return returnSuccess(recommendedCustomerList)
	}

	/**
	 * 查询患者
	 */
	@PostMapping("queryCustomer")
	@Transactional
	open fun queryCustomer(@RequestBody vo: CustomerSelectVo): ResponseBody {

		val page = iWebCompanyService.getCustomerPage(vo)
		for (info in page.records) {
			iCustomerInfoService.getMobileFirstStr(info)
			//上次就诊
			val lastRecordsDetail = iCustomerInfoService.getLastRecordsDetail(info.id)
			if (lastRecordsDetail != null) {
				if (lastRecordsDetail.masterUserId != null) {
					val doctor = iCompanyUserService.getUser(lastRecordsDetail.masterUserId!!)
					if (doctor != null) {
						info.lastRecordDetailDoctorName = doctor.realName
					}
				}
				if (lastRecordsDetail.secondaryUserId != null) {
					val secondaryUser = iCompanyUserService.getUser(lastRecordsDetail.secondaryUserId!!)
					if (secondaryUser != null) {
						info.lastSecondaryUserName = secondaryUser.realName
					}
				}
				val dept = iCompanyDeptService.getDept(lastRecordsDetail.deptId)
				if (dept != null) {
					info.lastSickRecordSubCompanyName = dept.name
				}
			}


			info.lastSickRecordTime = lastRecordsDetail?.startTime
		}
		return returnSuccess(page)
	}

	/**
	 * 患者分页
	 */
	@PostMapping("getCustomerPage")
	@PermsCode("customer:info:list")
	@Transactional
	open fun getCustomerPage(@RequestBody vo: CustomerSelectVo): ResponseBody {
		val page = iWebCompanyDeptService.getCustomerPage(vo)
		for (info in page.records) {
			iCustomerInfoService.getMobileFirstStr(info)
			//上次就诊
			val lastRecordsDetail = iCustomerInfoService.getLastRecordsDetail(info.id)
			if (lastRecordsDetail != null) {
				if (lastRecordsDetail.masterUserId != null) {
					val doctor = iCompanyUserService.getUser(lastRecordsDetail.masterUserId!!)
					if (doctor != null) {
						info.lastRecordDetailDoctorName = doctor.realName
					}
				}
				if (lastRecordsDetail.secondaryUserId != null) {
					val secondaryUser = iCompanyUserService.getUser(lastRecordsDetail.secondaryUserId!!)
					if (secondaryUser != null) {
						info.lastSecondaryUserName = secondaryUser.realName
					}
				}
				val dept = iCompanyDeptService.getDept(lastRecordsDetail.deptId)
				if (dept != null) {
					info.lastSickRecordSubCompanyName = dept.name
				}
			}


			info.lastSickRecordTime = lastRecordsDetail?.startTime
			info.hasArrearsOrder = iCustomerInfoService.customerHaveArrearsOrder(info.id)
		}
		return returnSuccess(page)
	}

	/**
	 * 修改基础信息
	 */
	@PostMapping("updateCustomerInfo")
	@PermsCode("customer:info:update")
	@Transactional
	open fun updateCustomerInfo(@RequestBody info: CustomerInfo): ResponseBody {
		//三级来源处理
		val customerSource = info.sourceInsert
		if (customerSource != null && customerSource.isNotEmpty()) {
			val sourceValues = customerSource.split("|")
			info.firstSource = sourceValues[0]
			if (sourceValues.size > 1) {
				info.secondSourceId = sourceValues[1].toLong()
			}
			if (sourceValues.size > 2) {
				val secondSource = iCustomerInfoService.getCustomerSecondSourceById(info.secondSourceId!!)
				if (secondSource != null) {
					when (secondSource.subType) {
						TypeEnum.CUSTOMER_INFO_SOURCE_COMPANY_USER -> {
							info.sourceCompanyUserId = sourceValues[2].toLong()
						}
						TypeEnum.CUSTOMER_INFO_SOURCE_CUSTOMER_INFO -> {
							info.sourceCustomerId = sourceValues[2].toLong()
						}
						else -> {
							info.sourceDistId = sourceValues[2].toLong()
						}
					}
				}
			}
		}
		val update = iCustomerInfoService.update(info)
		if (update.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return update
		}

		//设置手机和电话
		if (info.mobileNum != null) {
			val setMobile = iCustomerInfoService.setMobile(info.id, info.mobileNum!!)
			if (setMobile.bodyIsError()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return setMobile
			}
		}
		if (info.phone != null) {
			val setPhone = iCustomerInfoService.setPhone(info.id, info.phone!!)
			if (setPhone.bodyIsError()) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
				return setPhone
			}
		}

		return returnSuccess()
	}

	/**
	 * 设置关系人
	 */
	@PostMapping("setCustomerDeptUser")
	@Transactional(rollbackFor = [Exception::class])
	open fun setCustomerDeptUser(config: CustomerDeptConfig): ResponseBody {
		val bindCustomer = iWebCompanyDeptService.setDeptConfig(config)
		if (bindCustomer.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return bindCustomer
	}


	/**
	 * 获取患者类型
	 */
	@GetMapping("getCustomerTypeList")
	@Transactional
	open fun getCustomerTypeList(): ResponseBody {
		return returnSuccess(
			iCompanyDictionaryService.getCompanyDetailListToMapIdName(
				Constants.DistId.CUSTOMER_TYPE,
				getContext().companyId,
				getContext().subCompanyId
			)
		)
	}

	/**
	 * 获取分院客户
	 */
	@GetMapping("getSubCompanyCustomer")
	@Transactional
	open fun getSubCompanyCustomer(value: String?): ResponseBody {
		val customerSelectVo = CustomerSelectVo(queryValue = value)
		customerSelectVo.current = 1
		customerSelectVo.size = 10
		val customerPage = iWebCompanyDeptService.getCustomerPage(customerSelectVo)
		val list = customerPage.records
		if(list != null && list.isNotEmpty()){
			for(cus in list){
				val lastRecordsDetail = iCustomerInfoService.getLastRecordsDetail(cus.id)
				if(lastRecordsDetail?.masterUserId != null){
					cus.lastDoctorId = lastRecordsDetail.masterUserId
					val user = iCompanyUserService.getUser(lastRecordsDetail.masterUserId!!)
					if(user != null){
						cus.lastDoctorName = user.realName
					}
				}

			}
		}
		return returnSuccess(customerPage)
	}

	/**
	 * 查询客户
	 */
	@GetMapping("getCompanyCustomer")
	@Transactional
	open fun getCompanyCustomer(value: String?): ResponseBody {
		val vo = CustomerSelectVo(queryValue = value)
		vo.current = 1
		vo.size = 10
		return returnSuccess(
			iWebCompanyService.getCustomerPage(vo)
		)
	}

	/**
	 * 获取客户资料
	 */
	@GetMapping("getCustomerInfo/{id}")
	@Transactional
	open fun getCustomerInfo(@PathVariable id: Long): ResponseBody {
		//基础信息
		val info = iCustomerInfoService.getById(id) ?: return returnSuccess()
		iCustomerInfoService.getMobileFirstStr(info)
		val createUser = iCompanyUserService.getUser(info.createUserId)
		val vo = CustomerResultVo(
			id = info.id,
			name = info.name,
			gender = info.gender,
			historySickNum = info.historySickNum,
			createTime = info.createTime,
			remark = info.remark,
			mobileNum = info.mobileFirstNumStr,
			birthDate = info.birthDate,
		)
		vo.hasArrearsOrder = iCustomerInfoService.customerHaveArrearsOrder(id)
		if (createUser != null) {
			vo.createUserName = createUser.realName
		}

		// 其他信息（来源）

		if (info.otherJson != null) {
			val stringBuffer = StringBuffer()
			if (info.otherJson!!.getString("firstSource") != null && info.otherJson!!.getString("firstSource")
					.isNotEmpty()
			) {
				stringBuffer.append(info.otherJson!!.getString("firstSource") + " |")
			}
			if (info.otherJson!!.getString("secondSource") != null && info.otherJson!!.getString("secondSource")
					.isNotEmpty()
			) {
				stringBuffer.append(info.otherJson!!.getString("secondSource") + " |")
			}
			if (info.otherJson!!.getString("thirdSource") != null && info.otherJson!!.getString("thirdSource")
					.isNotEmpty()
			) {
				stringBuffer.append(info.otherJson!!.getString("thirdSource"))
			}
			vo.source = stringBuffer.toString()
		}

		vo.sourceShow = info.scoreShow

		//上次就诊
		val lastRecordsDetail = iCustomerInfoService.getLastRecordsDetail(id)
		if(lastRecordsDetail != null){
			vo.lastSickRecordTime = lastRecordsDetail.startTime
			vo.lastRecordsDetail = lastRecordsDetail
			if (lastRecordsDetail.masterUserId != null) {
				val doctor = iCompanyUserService.getUser(lastRecordsDetail.masterUserId!!)
				if (doctor != null) {
					vo.lastDoctorId = doctor.id
					vo.lastDoctorName = doctor.realName
				}
			}
			if (lastRecordsDetail.secondaryUserId != null) {
				val consultant = iCompanyUserService.getUser(lastRecordsDetail.secondaryUserId!!)
				if (consultant != null) {
					vo.lastConsultantId = consultant.id
					vo.lastConsultantName = consultant.realName
				}
			}

		}else{
			val customerDeptConfig = iWebCompanyDeptService.getCustomerDeptConfig(info.id, getContext().subCompanyId)
			if(customerDeptConfig != null){
				if(customerDeptConfig.firstChargeUserId != null){
					val doctor = iCompanyUserService.getUser(customerDeptConfig.firstChargeUserId!!)
					if (doctor != null) {
						vo.lastDoctorId = doctor.id
						vo.lastDoctorName = doctor.realName
					}
				}
				if(customerDeptConfig.secondChargeUserId != null){
					val consultant = iCompanyUserService.getUser(customerDeptConfig.secondChargeUserId!!)
					if (consultant != null) {
						vo.lastConsultantId = consultant.id
						vo.lastConsultantName = consultant.realName
					}
				}
			}
		}




		//当日预约
		val subscribeLog = iCustomerInfoService.getToDayCustomerSubscribeLog(id, getContext().subCompanyId)
		if (subscribeLog != null) {
			vo.toDaySubscribeStartTime = subscribeLog.subscribeTime
			vo.toDaySubscribeTime = subscribeLog.timeLength
			if(subscribeLog.doctorId != null){
				val cu = iCompanyUserService.getUser(subscribeLog.doctorId!!)
				if (cu != null) {
					vo.toDaySubscribeDoctorName = cu.realName
				}
			}
			if (subscribeLog.itemIdsShow != null && subscribeLog.itemIdsShow!!.isNotEmpty()) {
				val subscribeItemsByIds =
					iCustomerSubscribeLogService.getSubscribeItemsByIds(subscribeLog.itemIdsShow!!)
				val showBuffer = StringBuffer()
				for (i in subscribeItemsByIds) {
					showBuffer.append(i.itemName)
					showBuffer.append("|")
				}
				val str = showBuffer.toString()
				vo.toDaySubscribeItemNames = str.substring(0, str.length - 1)
			}

		}

		//订单项目显示规则
		vo.showRules = iCustomerInfoService.getShowRuleByOrderDetail(id, getContext().subCompanyId)
		vo.account = iCustomerInfoService.getCustomerAccount(id, getContext().subCompanyId)

		return returnSuccess(vo)
	}


	/**
	 * 获取用户患者(分页)
	 */
	@PostMapping("getUserCustomerPage")
	@PermsCode("customer:self:info:list")
	@Transactional
	open fun getUserCustomerPage(@RequestBody vo: CustomerSelectVo): ResponseBody {

		return returnSuccess(iWebCompanyUserService.getSelfCustomerPage(Page(vo.current, vo.size), vo))
	}

	/**
	 * 添加患者关系人
	 */
	@PostMapping("addAssociatedCustomer")
	@Transactional(rollbackFor = [Exception::class])
	open fun addAssociatedCustomer(@RequestBody associated: CustomerInfoAssociated): ResponseBody {
		val addAssociatedCustomer = iCustomerInfoService.addAssociatedCustomer(associated)
		if (addAssociatedCustomer.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return addAssociatedCustomer
		}
		return returnSuccess()
	}

	/**
	 * 修改患者之间关系
	 */
	@PostMapping("updateAssociated")
	@Transactional(rollbackFor = [Exception::class])
	open fun updateAssociated(@RequestBody associated: CustomerInfoAssociatedUpdateVo): ResponseBody {
		val updateCustomerAssociated = iCustomerInfoService.updateCustomerAssociated(associated)
		if (updateCustomerAssociated.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return updateCustomerAssociated
		}
		return returnSuccess()
	}

	/**
	 * 删除患者之间关系
	 */
	@PostMapping("delAssociated/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun delAssociated(@PathVariable id: Long): ResponseBody {
		val delAssociatedCustomer = iCustomerInfoService.delAssociatedCustomer(id)
		if (delAssociatedCustomer.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
			return delAssociatedCustomer
		}
		return returnSuccess()
	}

	/**
	 * 获取患者关系人
	 */
	@GetMapping("getAssociatedCustomerList/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun getAssociatedCustomerList(@PathVariable id: Long): ResponseBody {
		val list = iCustomerInfoService.getAssociatedList(id)
		for (ass in list) {
			val assCustomerId = if (ass.customerId == id) {
				ass.associatedCustomerId
			} else {
				ass.customerId
			}
			iCustomerInfoService.getJoinInfoByCustomerId(assCustomerId, ass)
		}
		return returnSuccess(list)
	}

	/**
	 * 获取患者关系类型
	 */
	@GetMapping("getCustomerAssociatedNameSelect")
	@Transactional
	open fun getCustomerAssociatedNameSelect(): ResponseBody {
		return returnSuccess(
			iCompanyDictionaryService.getCompanyDetailListToMap(
				Constants.DistId.CUSTOMER_TO_CUSTOMER_ASSOCIATED,
				getContext().companyId,
				getContext().subCompanyId
			)
		)
	}


	/**
	 * 获取病历号
	 */
	@GetMapping("createHistoryNum")
	@Transactional
	open fun createHistoryNum(): ResponseBody {
		val newNum =
			iSysNumGeneratorService.getNewNum(
				getContext().companyId,
				TypeEnum.SYS_NUM_GENERATOR_SICK,
				getContext().subCompanyId
			)
		return returnSuccess(newNum.numShow)
	}

	/**
	 * 刷新病历号码
	 */
	@GetMapping("refreshHistoryNum")
	@Transactional
	open fun refreshHistoryNum(): ResponseBody {
		val newNum =
			iSysNumGeneratorService.getNewNum(
				getContext().companyId,
				TypeEnum.SYS_NUM_GENERATOR_SICK,
				getContext().subCompanyId
			)
		if (iWebCompanyService.haveSameHistoryNum(newNum.numShow)) {
			iSysNumGeneratorService.useSysNum(
				getContext().companyId,
				TypeEnum.SYS_NUM_GENERATOR_SICK,
				null,
				newNum.numShow
			)
			return returnSuccess(
				iSysNumGeneratorService.getNewNum(
					getContext().companyId,
					TypeEnum.SYS_NUM_GENERATOR_SICK,
					getContext().subCompanyId
				).numShow
			)
		}

		return returnSuccess(newNum.numShow)
	}

	/**
	 * 添加查询用户记录
	 */
	@PostMapping("addSelectLog")
	@Transactional(rollbackFor = [Exception::class])
	open fun addSelectLog(@RequestBody selectLog: CompanyUserCustomerSelectLog): ResponseBody {
		val addSelectCustomerLog = iWebCompanyUserService.addSelectCustomerLog(
			selectLog
		)
		if (addSelectCustomerLog.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return addSelectCustomerLog
	}

	/**
	 * 查询用户查询患者记录
	 */
	@PostMapping("getSelectLogPage")
	@Transactional
	open fun getSelectLogPage(@RequestBody vo: CompanyUserCustomerSelectLogSelectVo): ResponseBody {
		val page = iWebCompanyUserService.getSelectCustomerLogPage(vo)
		for (info in page.records) {
			iCustomerInfoService.getJoinInfoByCustomerId(info.customerId, info)
		}
		return returnSuccess(page)
	}

	/**
	 * 删除查看患者记录
	 */
	@PostMapping("deleteSelectLogByCustomerId/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun deleteSelectLogByCustomerId(@PathVariable id: Long): ResponseBody {
		val deleteSelectCustomerLog = iWebCompanyUserService.deleteSelectCustomerLog(getContext().userId, id)
		if (deleteSelectCustomerLog.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return deleteSelectCustomerLog
	}


	//二级来源

	/**
	 * 二级来源获取
	 */
	@GetMapping("getCustomerSecondSourceListByType/{parentValue}")
	@Transactional
	open fun getCustomerSecondSourceListByType(@PathVariable parentValue: String): ResponseBody {
		return returnSuccess(iCustomerInfoService.getCustomerSecondSourceList(getContext().companyId, parentValue))
	}

	@PostMapping("getCustomerSecondSourceList")
	@Transactional
	open fun getCustomerSecondSourceList(@RequestBody vo: CustomerInfoSecondSourceDistSelectVo): ResponseBody {
		return returnSuccess(iCustomerInfoService.getCustomerSecondSourceList(getContext().companyId, vo.parentValue))
	}

	//子来源类型（第三层的类型）
	@GetMapping("getCustomerSecondSourceSubType")
	@Transactional
	open fun getCustomerSecondSourceSubType(): ResponseBody {
		val resList = mutableListOf<Map<String, Any>>()
		resList.add(TypeEnum.CUSTOMER_INFO_SOURCE_DIST.getMap())
		resList.add(TypeEnum.CUSTOMER_INFO_SOURCE_COMPANY_USER.getMap())
		resList.add(TypeEnum.CUSTOMER_INFO_SOURCE_CUSTOMER_INFO.getMap())
		return returnSuccess()
	}

	/**
	 * 添加二级来源字典
	 */
	@PostMapping("addCustomerInfoSecondSource")
	@Transactional(rollbackFor = [Exception::class])
	open fun addCustomerInfoSecondSource(@RequestBody dist: CustomerInfoSecondSource): ResponseBody {

		val addCustomerSourceDist = iCustomerInfoService.addCustomerSecondSource(dist)
		if (addCustomerSourceDist.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}

		return addCustomerSourceDist
	}


	/**
	 * 修改二级来源字典
	 */
	@PostMapping("updateCustomerInfoSecondSource")
	@Transactional(rollbackFor = [Exception::class])
	open fun updateCustomerInfoSecondSource(@RequestBody dist: CustomerInfoSecondSource): ResponseBody {
		val updateCustomerSourceDist = iCustomerInfoService.updateCustomerSecondSource(dist)
		if (updateCustomerSourceDist.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return updateCustomerSourceDist
	}

	/**
	 * 删除二级来源字典
	 */
	@PostMapping("delCustomerSecondSource/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun delCustomerSecondSource(@PathVariable id: Long): ResponseBody {
		val delCustomerSecondSource = iCustomerInfoService.delCustomerSecondSource(id)
		if (delCustomerSecondSource.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}
		return delCustomerSecondSource
	}

	//患者来源三级获取

	@GetMapping("getCustomerSourceDistListByType/{parentId}")
	@Transactional
	open fun getCustomerSourceDistListByType(@PathVariable parentId: Long): ResponseBody {
		return returnSuccess(iCustomerInfoService.getCustomerSourceDistList(getContext().companyId, parentId))
	}

	@PostMapping("getCustomerSourceDistList")
	@Transactional
	open fun getCustomerSourceDistList(@RequestBody vo: CustomerInfoSourceDistSelectVo): ResponseBody {
		return returnSuccess(iCustomerInfoService.getCustomerSourceDistList(getContext().companyId, vo.parentId))
	}


	/**
	 * 添加来源字典
	 */
	@PostMapping("addCustomerSourceDist")
	@Transactional(rollbackFor = [Exception::class])
	open fun addCustomerSourceDist(@RequestBody dist: CustomerInfoSourceDist): ResponseBody {
		val addCustomerSourceDist = iCustomerInfoService.addCustomerSourceDist(dist)
		if (addCustomerSourceDist.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}

		return addCustomerSourceDist
	}

	/**
	 * 修改来源字典
	 */
	@PostMapping("updateCustomerSourceDist")
	@Transactional(rollbackFor = [Exception::class])
	open fun updateCustomerSourceDist(@RequestBody dist: CustomerInfoSourceDist): ResponseBody {
		val updateCustomerSourceDist = iCustomerInfoService.updateCustomerSourceDist(dist)
		if (updateCustomerSourceDist.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}

		return updateCustomerSourceDist
	}

	/**
	 * 删除来源字典
	 */
	@PostMapping("delCustomerSourceDist/{id}")
	@Transactional(rollbackFor = [Exception::class])
	open fun delCustomerSourceDist(@PathVariable id: Long): ResponseBody {
		val delCustomerSourceDist = iCustomerInfoService.delCustomerSourceDist(id)
		if (delCustomerSourceDist.bodyIsError()) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly()
		}

		return delCustomerSourceDist
	}

	/**
	 * 获取患者手机类型
	 */
	@GetMapping("getCustomerMobileType")
	@Transactional
	open fun getCustomerMobileType(): ResponseBody {
		val list = mutableListOf<Map<String, Any>>()
		list.add(mapOf(Pair("id", CUSTOMER_MOBILE_TO_CUSTOMER_TYPE_SELF_ID), Pair("name", CUSTOMER_MOBILE_SELF)))
		val dist = iCompanyDictionaryService.getCompanyDetailListToMapIdName(
			Constants.DistId.CUSTOMER_MOBILE_TO_CUSTOMER_TYPE,
			getContext().companyId,
			getContext().subCompanyId
		)
		if (dist.isNotEmpty()) {
			list.addAll(dist)
		}
		return returnSuccess(list)
	}

	/**
	 * 获取患者座机类型
	 */
	@GetMapping("getCustomerPhoneType")
	@Transactional
	open fun getCustomerPhoneType(): ResponseBody {
		return returnSuccess(
			iCompanyDictionaryService.getCompanyDetailListToMapIdName(
				Constants.DistId.CUSTOMER_PHONE_TO_CUSTOMER_TYPE,
				getContext().companyId,
				getContext().subCompanyId
			)
		)
	}

	@GetMapping("refreshLastRecordDetailId")
	@Transactional(rollbackFor = [Exception::class])
	open fun refreshLastRecordDetailId():ResponseBody{
		val customerList = iWebCompanyService.getCustomerList(CustomerSelectVo())
		for(info in customerList){
			iCustomerInfoService.refreshLastRecordsDetailId(info.id)
		}
		return returnSuccess()
	}

//	@GetMapping("sendMessage")
//	@Transactional(rollbackFor = [Exception::class])
//	open fun sendMessage():ResponseBody{
//		val config = JSONObject()
//		config["phone"] = "15979116070"
//		config["templateId"] = "1204237"
//		config["appId"] = "1400598747"
//		val msgBody = JSONObject()
//		msgBody["message"] = "123456"
//
//		SendMessageHandler.messages.add(
//			ToUserMessageVo(
//				UserType.Custom, getContext().companyId,msgBody,true, listOf(604)
//			)
//		)
//		return returnSuccess()
//	}


}
